/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.business;

import TimeRecording.tables.Badge;
import TimeRecording.tables.ClockedPeriod;
import TimeRecording.tables.Employee;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author david
 */
public class BadgeMaintenance {

    private final static int DEFAULT_NO_OF_DAYS_HOUSEKEEPING = 7;
    
    private EntityManager entityManager;

    public BadgeMaintenance(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    /**
     * This method will retro-fit employee IDs to clocking period records that
     * have reference a recognised badge but no employee.  This is to cater for
     * the occasions when a badge is given to an employee as a loan but it not
     * assigned to the employee within the system.
     *
     * The number of days specified controls how far back we search.
     *
     * @param noOfDays the number of days to look back for clocked time that
     *        is associated with an unallocated badge.
     */
    public void housekeeping(Integer noOfDays) {

        if (noOfDays == null) {
            noOfDays = DEFAULT_NO_OF_DAYS_HOUSEKEEPING;
        }
        
        GregorianCalendar cal = new GregorianCalendar();
        cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
        cal.set(GregorianCalendar.MINUTE, 0);
        cal.set(GregorianCalendar.SECOND, 0);
        cal.set(GregorianCalendar.MILLISECOND, 0);
        cal.add(GregorianCalendar.DATE, -noOfDays);
        Date date = cal.getTime();
        
        List<ClockedPeriod> periods = ClockedPeriod.
                getClockedPeriodsMissingAnEmployee(entityManager, date);

        if (periods.isEmpty()) {
            return;
        }

        HashMap<Integer, Employee> badgeMap = Badge.getBadgeMap(entityManager);

        for (ClockedPeriod period : periods) {

            Employee employee = badgeMap.get(
                    period.getClockedPeriodPK().getBadgeId());

            if (employee != null) {
                period.setEmployeeId(employee);
                entityManager.persist(period);
            }
        }
    }
}
